package servlet.reader;

import entity.Books;
import entity.Pages;
import com.alibaba.fastjson.JSONObject;
import service.reader.BooksService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * BooksServlet
 *
 * @author lenovo
 * @since 2023/8/30
 */
@WebServlet("/reader/book")
public class BooksServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    BooksService service = new service.reader.impl.BooksService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        resp.setContentType("application/json; charset=UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 接收参数
        String limit = req.getParameter("limit");
        String page = req.getParameter("page");
        String condition = (String) req.getParameter("condition");
        String conditionValue = (String) req.getParameter("conditionValue");

        PrintWriter out = resp.getWriter();
        if (page == null) {
            page = "1";
        }
        if (limit == null) {
            limit = "10";
        }

        // 准备返回参数
        int code = 0;
        String msg = "无数据";
        int count = 0;

        //创建page对象
        Pages<Books> booksPages = new Pages<>();
        booksPages.setPageSize(Integer.valueOf(limit));
        booksPages.setPageCountNo(Integer.valueOf(page));
        booksPages.setPageCount(service.pageCount(condition,conditionValue));
        count = booksPages.getPageCount();
        //获取list对象
        List<Books> list = service.getList(condition,conditionValue,booksPages);
        if (list == null){
            code = 1;
        }
        booksPages.setList(list);



        //创建JSON对象
        JSONObject jsonResult = new JSONObject();

        jsonResult.put("code",code);
        jsonResult.put("count",count);
        jsonResult.put("msg",msg);
        jsonResult.put("data",booksPages.getList());

        out.print(jsonResult.toJSONString());
    }
}
